import time


import asyncio
import aiohttp
import requests

urls = [f'https://httpbin.org/get?age = {i}'for i  in range(10)]
start = time.time()
#同步
for url in urls:
    response = requests.get(url)
    print(response.json())

end = time.time()
print(f'同步耗时: {end - start}')


# async def fetch(session, url):
#     async with session.get(url) as response:
#         data = await response.json()
#         print(data['args'])
#         return data
#
# async def async_fetch():
#     async with aiohttp.ClientSession() as session:
#         tasks = [fetch(session, url) for url in urls]
#         await asyncio.gather(*tasks)
#
#
# start = time.time()
# asyncio.run(async_fetch())
# end  = time.time()
# print(f'异步耗时: {end - start}')


# async def task1():
#     print('task1')
#     await asyncio.sleep(1)
#     print('task1 done')
#
#
# async def task2():
#     print('task2')
#     await asyncio.sleep(3)
#     print('task2 done')
#
#
# async def main():
#     await asyncio.gather(task1(), task2())
#
#
# start = time.time()
# asyncio.run(main())
# end = time.time()
# print(f'耗时: {end - start}')
#
# #执行相似任务
# async def task(name):
#     print(f'{name} start')
#     await asyncio.sleep(1)
#     print(f'{name} done')
# async def main():
#     tasks = [task(i) for i in range(10)]
#     await asyncio.gather(*tasks)
#
# asyncio.run(main())

# urls = [f'https://httpbin.org/get?age = {i}'for i  in range(10)]

# async def main():
#     async with aiohttp.ClientSession() as session:
#         async with session.get(f'https://httpbin.org/get?age = {1}') as response:
#             return await response.json()
#
# start = time.time()
# print(asyncio.run(main()))
# print(f'耗时: {time.time() - start}')


async def fetch(session,url):
    async with session.get(url) as response:
        return await response.json()

async def main():
    async with aiohttp.ClientSession() as session:
        urls = [f'https://httpbin.org/get?age = {i}'for i  in range(10)]
        result = await asyncio.gather(*[fetch(session, url) for url in urls])
        for data in result:
           print(data)


start = time.time()
asyncio.run(main())
print(f'耗时: {time.time() - start}')
